package com.genius.reservation.common.jwtUtil;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.genius.reservation.common.GlobalExceptionHandler.TokenException;
import com.genius.reservation.user.entity.UserInformation;
import com.genius.reservation.user.service.IUserInformationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class jwtTool implements jwtInterface{
    @Value("${jwtKey}")
    String jwtKey;
    @Autowired
    IUserInformationService userservice;
    public String createToken(UserInformation user){
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, 10);
        Map<String,Object> payload = new HashMap<String,Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("usernumber", user.getUserNumber());
//        payload.put("password", user.getCreateTime());
        return JWTUtil.createToken(payload, jwtKey.getBytes());
    }

    public boolean validateToken(String token) {
        return JWTUtil.verify(token, jwtKey.getBytes());
    }

    public JSONObject parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        JWTPayload payload = jwt.getPayload();
        return JSONObject.parseObject(payload.toString());
    }

    public boolean validateTimeToken(String token) {
        return JWTUtil.parseToken(token).validate(0);
    }

    public UserInformation validateAndParse(String token) {
//        if (validateToken(token)) {
//            if (validateTimeToken(token)){
//                JSONObject jsonObject = parseToken(token);
//                String username = (String) jsonObject.get("usernumber");
//                UserInformation one = userservice.lambdaQuery().eq(UserInformation::getUserNumber, username).one();
//                if (one.judgeNull()) {
//                    throw new TokenException(400,"token解析失败");
//                }
//                return one;
//            }
//        }
        return null;
    }
}
